package com.rakuten.api.mule.transformers;

import java.util.ArrayList;
import java.util.List;

import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.api.transport.PropertyScope;
import org.mule.transformer.AbstractMessageTransformer;

import com.rakuten.api.mule.CommonFlowConstants;
import com.rakuten.api.mule.model.Product;
import com.rakuten.api.mule.model.Variant;
import com.rakuten.api.mule.response.AddProductResponseRMS;

public class BuildAddProductResponse extends AbstractMessageTransformer {

	public BuildAddProductResponse() {

	}

	@Override
	public Object transformMessage(MuleMessage message, String outputEncoding)
			throws TransformerException {
		try {
			com.rakuten.api.mule.model.rms.Product product = message
					.getProperty(CommonFlowConstants.PRODUCT_INFO,
							PropertyScope.SESSION);
			// return product to payload

			AddProductResponseRMS productResponseRms = message
					.getPayload(AddProductResponseRMS.class);
			if (productResponseRms.equals(CommonFlowConstants.STATUS_SUCCESS)) {

				Product productResponse = new Product();
				productResponse.setBaseSku(product.getBaseSku());
				List<Variant> variants = new ArrayList<>();
				for (com.rakuten.api.mule.model.rms.Variant variant : product
						.getVariants()) {
					Variant newVariant = new Variant();
					newVariant.setSku(variant.getSku());
					variants.add(newVariant);
				}
				productResponse.setVariants(variants);
				productResponse.setFreeShipping(null);
				message.setPayload(productResponse);
			} else {
				message.setPayload(productResponseRms.getError());
			}

		} catch (Exception e) {
			throw new TransformerException(this, e);
		}

		return message;
	}

}
